package com.arcaneshift.servlet.abstracts;

import java.util.List;

import com.arcaneshift.model.action.game.BattleEngine;
import com.arcaneshift.model.action.game.BattlePlayer;
import com.arcaneshift.model.response.StoryResponse;
import com.arcaneshift.servlet.util.game.Story;
import com.arcaneshift.servlet.util.network.RequestAction;
import com.arcaneshift.servlet.util.parser.StoryXMLParser;
import com.common.security.exceptions.ParserException;
import com.common.servlet.abstracts.AbstractParserServlet;
import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;

public abstract class AbstractGameServlet extends AbstractParserServlet {
	private static final long serialVersionUID = 1L;

	protected void sendPlayerActions(BattleEngine game) {
		try {
			List<BattlePlayer> players = game.getBattlePlayers();
			BattlePlayer battlePlayer;
			
			for (int i = 0; i < players.size(); i++) {
				battlePlayer = players.get(i);
				if (battlePlayer.getPlayer().getChannel() != null) {
					sendChannelResponse(battlePlayer.getPlayer().getSession().
							getUserId(), createActionResponse(battlePlayer.getStories()));
					battlePlayer.clearStories();
				}
			}
			
			/*
			if (game.getPlayer1().getChannel() != null) {
				sendChannelResponse(game.getPlayer1().getSession().getUserId(), createActionResponse(game.getPlayer1Stories()));
				//delete the actions from the game
			}
			if (game.getPlayer2().getChannel() != null) {
				sendChannelResponse(game.getPlayer2().getSession().getUserId(), createActionResponse(game.getPlayer2Stories()));
				//delete the actions from the game
			}
			*/
		} catch (ParserException e) {
			//TODO manage parser errors
			e.printStackTrace();
		}
	}
	
	private StoryResponse createActionResponse(List<Story> actions) {
		StoryResponse response = new StoryResponse();
		response.setRequestAction(RequestAction.GAME_UPDATE);
		response.setStories(actions);
		
		return response;
	}
	
	private void sendChannelResponse(Long token, StoryResponse response) throws ParserException {
		ChannelService service = ChannelServiceFactory.getChannelService();
		StoryXMLParser gameParser = new StoryXMLParser();
		service.sendMessage(new ChannelMessage(token.toString(), gameParser.parseResponse(response)));
	}
}
